package wsclient;

import org.apache.cxf.endpoint.Client;
import org.apache.cxf.jaxws.JaxWsProxyFactoryBean;
import org.apache.cxf.jaxws.endpoint.dynamic.JaxWsDynamicClientFactory;
import wsserver.SimpleServiceDemo;

/**
 * Created by lijian on 2020/11/21.
 */
public class WSClient {

    // 动态调用, 客户端不需要接口类
    public void dynamicInvoke() {
        // 创建动态客户端
        JaxWsDynamicClientFactory dcf = JaxWsDynamicClientFactory.newInstance();
        Client client = dcf.createClient("http://localhost:8080/services/ws/simpleService?wsdl");
        // 需要密码的情况需要加上用户名和密码
        // client.getOutInterceptors().add(new ClientLoginInterceptor(USER_NAME, PASS_WORD));
        Object[] objects = new Object[0];
        try {
            // invoke("方法名", 参数1, 参数2, 参数3....);
            //这里注意如果是复杂参数的话，要保证复杂参数可以序列化
            objects = client.invoke("doService", "动态调用测试");
            System.out.println("返回数据:" + objects[0]);
        } catch (java.lang.Exception e) {
            e.printStackTrace();
        }
    }

    // 静态调用,客户端需要接口类
    public void staticInvoke() {
        // 接口地址
        String address = "http://localhost:8080/services/ws/simpleService?wsdl";
        // 代理工厂
        JaxWsProxyFactoryBean jaxWsProxyFactoryBean = new JaxWsProxyFactoryBean();
        // 设置代理地址
        jaxWsProxyFactoryBean.setAddress(address);
        // 设置接口类型
        jaxWsProxyFactoryBean.setServiceClass(SimpleServiceDemo.class);

        // 创建一个代理接口实现
        SimpleServiceDemo us = (SimpleServiceDemo) jaxWsProxyFactoryBean.create();
        // 数据准备
        String data = "静态调用测试";
        // 调用代理接口的方法调用并返回结果
        String result = us.doService(data);
        System.out.println("返回结果:" + result);
    }

    public static void main(String[] args) {
        WSClient client = new WSClient();
        client.staticInvoke();
        client.dynamicInvoke();
    }


}
